import { createWebHistory, createRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { routes } from '@/route/routes'

export const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    // 始终滚动到顶部
    return { top: 0, behavior: 'smooth' }
  },
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 引入用户仓库
  const userStore = useUserStore()
  // 获取用户token
  const token = userStore.token
  if (to.name === 'LoginView') {
    next()
  } else if (token) {
    next()
  } else {
    next({ name: 'LoginView' })
  }
})
